package com.seari.custody.util;

import com.seari.custody.bean.User;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.ExpiredJwtException;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.stereotype.Component;

import java.util.*;

@Component
public class JwtTokenUtils {

    public static final String TOKEN_HEADER = "Authorization";
    public static final String TOKEN_PREFIX = "Bearer ";

    public static final String SUBJECT = "congge";

    public static final long EXPIRITION = 1000 * 3600 *365;

    public static final String APPSECRET_KEY = "JOVENOLY2018";

    private static final String ROLE_CLAIMS = "rol";

    public static String generateJsonWebToken(User user) {

        if (user.getUuid() == null || user.getUserNumber()== null) {
            return null;
        }

        Map<String,Object> map = new HashMap<>();
        map.put(ROLE_CLAIMS, "rol");

        String token = Jwts
                .builder()
                .setSubject(SUBJECT)
                .setClaims(map)
                .claim("userId", user.getUserNumber())
                .claim("userIds", user.getUuid())
                .setIssuedAt(new Date())
                .setExpiration(new Date(System.currentTimeMillis() + EXPIRITION))
                .signWith(SignatureAlgorithm.HS256, APPSECRET_KEY).compact();
        return token;
    }

//    /**
//     * 生成token
//     * @param username
//     * @param role
//     * @return
//     */
//    public static String createToken(String username,String role) {
//
//        Map<String,Object> map = new HashMap<>();
//        map.put(ROLE_CLAIMS, role);
//
//        String token = Jwts
//                .builder()
//                .setSubject(username)
//                .setClaims(map)
//                .claim("username",username)
//                .setIssuedAt(new Date())
//                .setExpiration(new Date(System.currentTimeMillis() + EXPIRITION))
//                .signWith(SignatureAlgorithm.HS256, APPSECRET_KEY).compact();
//        return token;
//    }

    //不管是否过期，都返回claims对象
    public static Claims checkJWT(String token){
        Claims claims;
        try {
            claims = Jwts.parser()
                    .setSigningKey(APPSECRET_KEY) // 设置标识名
                    .parseClaimsJws(token)  //解析token
                    .getBody();
        } catch (ExpiredJwtException e) {
            claims = e.getClaims();
        }
        return claims;
    }


    /**
     * 获取用户ID
     * uuid
     * @param token
     * @return
     */
    public static String getUserId(String token){
        Claims claims = Jwts.parser().setSigningKey(APPSECRET_KEY).parseClaimsJws(token).getBody();
        return claims.get("userIds").toString();
    }

    /**
     * 获取用户ID 技审用户ID
     * @param token
     * @return
     */
    public static String getUserNumber(String token){
        Claims claims = Jwts.parser().setSigningKey(APPSECRET_KEY).parseClaimsJws(token).getBody();
        return claims.get("userId").toString();
    }

    /**d
     * 获取用户角色
     * @param token
     * @return
     */
    public static String getUserRole(String token){
        Claims claims = Jwts.parser().setSigningKey(APPSECRET_KEY).parseClaimsJws(token).getBody();
        return claims.get("rol").toString();
    }

    /**
     * 是否过期
     * @param token
     * @return
     */
    public static boolean isExpiration(String token){
        Claims claims;
        try {
            claims = Jwts.parser().setSigningKey(APPSECRET_KEY).parseClaimsJws(token).getBody();
            return claims.getExpiration().before(new Date());
        }catch (ExpiredJwtException e){
            return true;
        }
    }

//    public static void main(String[] args) {
//        String name = "acong";
//        String role = "rol";
//        //String token = createToken(name,role);
//        String token = "eyJhbGciOiJIUzI1NiJ9.eyJleHAiOjE2MTYxNjM3NTUsImlhdCI6MTYxNjE2MDE1NSwicm9sIjoiW10iLCJ1c2VybmFtZSI6ImFkbWluIn0.kRbMfKf_2Kt5KU03kXV7yCU_1CFHLDGUYK0U6hVnFyM";
//        System.out.println(token);
//
//        Claims claims = checkJWT(token);
//        System.out.println(claims.get("username"));
//
//        System.out.println(getUsername(token));
//        System.out.println(getUserRole(token));
//        System.out.println(isExpiration(token));
//
//    }


    /**
     * eyJhbGciOiJIUzI1NiJ9.
     * eyJzdWIiOiJjb25nZ2UiLCJpZCI6IjExMDExIiwibmFtZSI6Im51b3dlaXNpa2kiLCJpbWciOiJ3d3cudW9rby5jb20vMS5wbmciLCJpYXQiOjE1NTQ5OTI1NzksImV4cCI6MTU1NTU5NzM3OX0.
     * 6DJ9En-UBcTiMRldZeevJq3e1NxJgOWryUyim4_-tEE
     *
     *
     * eyJhbGciOiJIUzI1NiJ9.
     * eyJleHAiOjE2MTU5NjI4OTYsImlhdCI6MTYxNTk2Mjg2Niwicm9sIjoicm9sZV9hZG1pbiIsInVzZXJuYW1lIjoiYWRtaW4ifQ.
     * x4ae3S5zT6EhLfu4Mw2ljdYgHP-O4Vv5V4AiTylGNWY
     * @param args
     */



	public static void main(String[] args) {

//        User user = new User();
//        user.setUuid("");
//        user.setUsername("nuoweisiki");
//        String token = "eyJhbGciOiJIUzI1NiJ9.eyJuYW1lIjoiYWRtaW4iLCJpZCI6MSwiZXhwIjoxNjE4NTEzOTg3LCJpYXQiOjE2MTcxOTk5ODcsInJvbCI6InJvbCJ9._iB5_bR_5Pzu8PCG59QVl7OHT_r3-T9aUjFtE1GkoWMs";
//        //String token = JwtTokenUtils.generateJsonWebToken(user);
//        System.out.println(token);
//
//        Claims claims = checkJWT(token);
//        if (claims != null) {
//         //   String id = getUsername(token);
//            String name = claims.get("name").toString();
//
//            String rol = claims.get("rol").toString();
//
//          //  System.out.println("id:" + id);
//            System.out.println("name:" + name);
//
//            System.out.println("rol:" + rol);
//        }

        Claims claims = JwtTokenUtils.checkJWT("eyJ0eXBlIjoiSldUIiwiYWxnIjoiSFMyNTYifQ.eyJ1c2VySWQiOiJhZG1pbiIsInVybCI6Imh0dHA6MTI3LjAuMC4xOjgwODAvTU1TT0EiLCJleHAiOjE2MzA5OTYzMTZ9.rsXuADIzPA95pgmrgKvQQJMmcEdU0fUKd_QSnQZCInc");

        String userId = claims.get("userId", String.class);
        System.out.println(userId);




    }
}


